import React, { useState } from 'react';

interface FilePreviewProps {
  files: string | string[];
  multiple?: boolean;
  onRemove: (url: string) => void;
}

const FilePreview: React.FC<FilePreviewProps> = ({ files, multiple = false, onRemove }) => {
  const fileList = multiple ? (files as string[]) : [files as string].filter(Boolean);

  if (fileList.length === 0) {
    return null;
  }

  // 单个文件预览组件
  const SingleFilePreview: React.FC<{ url: string }> = ({ url }) => {
    const [imageError, setImageError] = useState(false);
    const [videoError, setVideoError] = useState(false);

    // 判断文件类型
    const getFileType = (url: string) => {
      const extension = url.split('.').pop()?.toLowerCase();
      if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp'].includes(extension || '')) {
        return 'image';
      }
      if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv'].includes(extension || '')) {
        return 'video';
      }
      return 'other';
    };

    const fileType = getFileType(url);
    const fileName = url.split('/').pop() || 'Unknown';

    const handleRemove = (e: React.MouseEvent) => {
      e.stopPropagation();
      onRemove(url);
    };

    return (
      <div className="relative group inline-block mr-2 mb-2">
        <div className="relative w-20 h-20 bg-gray-100 rounded-lg overflow-hidden border border-gray-200">
          {/* 删除按钮 */}
          <button
            onClick={handleRemove}
            className="absolute top-1 right-1 z-10 w-5 h-5 bg-red-500 text-white rounded-full text-xs flex items-center justify-center hover:bg-red-600 opacity-0 group-hover:opacity-100 transition-opacity"
          >
            ×
          </button>

          {/* 文件预览 */}
          {fileType === 'image' && !imageError ? (
            <img
              src={url}
              alt={fileName}
              className="w-full h-full object-contain"
              onError={() => setImageError(true)}
            />
          ) : fileType === 'video' && !videoError ? (
            <video
              src={url}
              className="w-full h-full object-contain"
              onError={() => setVideoError(true)}
              muted
            />
          ) : (
            <div className="w-full h-full flex items-center justify-center">
              <span className="text-2xl">
                {fileType === 'video' ? '🎬' : '📄'}
              </span>
            </div>
          )}
        </div>

        {/* 文件名提示 */}
        <div className="absolute bottom-0 left-0 right-0 bg-black bg-opacity-75 text-white text-xs p-1 opacity-0 group-hover:opacity-100 transition-opacity truncate">
          {fileName}
        </div>
      </div>
    );
  };

  return (
    <div className="mt-2">
      <div className="flex flex-wrap">
        {fileList.map((url, index) => (
          <SingleFilePreview key={`${url}-${index}`} url={url} />
        ))}
      </div>
    </div>
  );
};

export default FilePreview; 